package photorganizer.common.bean;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import photorganizer.common.helper.CollectionHelper;
import photorganizer.common.helper.ReflectHelper;


public class Request {

	private final Object proxy;

	private final Object bean;

	private final Method method;

	private final Object[] parameters;

	private final Iterator<Interceptor> interceptors;

	Request(Object proxy, Object bean, Method method, Object[] parameters, List<Interceptor> interceptors) {
		this.proxy = proxy;
		this.bean = bean;
		this.method = method;
		this.parameters = parameters;
		this.interceptors = CollectionHelper.iterator(interceptors);
	}

	public Object getProxy() {
		return proxy;
	}

	public Object getBean() {
		return bean;
	}

	public Method getMethod() {
		return method;
	}

	public Object[] getParameters() {
		return parameters;
	}

	public final Object invoke() throws Throwable {
		if (interceptors.hasNext()) {
			Interceptor interceptor = interceptors.next();
			return interceptor.invoke(this);
		}

		Class<?> beanInterface = method.getDeclaringClass();
		Class<?> beanClass = bean.getClass();
		Method beanMethod = null;

		if (beanInterface.isAssignableFrom(beanClass)) {
			beanMethod = method;
		}
		else {
			beanMethod = ReflectHelper.getDeclaredMethod(beanClass, method.getName(), method.getParameterTypes());
		}

		return ReflectHelper.invoke(beanMethod, bean, parameters);
	}

}
